<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{
    /**
     * 显示用户中心页面
     */
    public function profile()
    {
        return view('user.profile');
    }

    /**
     * 更新用户个人信息
     */
    public function updateProfile(Request $request)
    {
        try {
            $user = Auth::user();

            // 验证输入数据
            $validator = Validator::make($request->all(), [
                'nickname' => 'nullable|string|max:10',
//                'phone' => 'nullable|string|max:20|regex:/^1[3-9]\d{9}$/|unique:users,phone,' . $user->id,
//                'email' => 'required|email|max:255|unique:users,email,' . $user->id,
                'avatar' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            ], [
                'nickname.max' => '昵称不能超过10个字符',
                'phone.regex' => '请输入正确的手机号格式',
                'phone.unique' => '手机号已被使用',
                'email.required' => '邮箱不能为空',
                'email.email' => '请输入正确的邮箱格式',
                'email.unique' => '邮箱已被使用',
                'avatar.image' => '头像必须是图片文件',
                'avatar.mimes' => '头像只支持jpeg、png、jpg、gif格式',
                'avatar.max' => '头像大小不能超过2MB',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 处理头像上传
            $updateData = [
                'nickname' => $request->nickname,
//                'phone' => $request->phone,
//                'email' => $request->email,
            ];

            if ($request->hasFile('avatar')) {
                // 删除旧头像
                if ($user->avatar && Storage::disk('public')->exists($user->avatar)) {
                    Storage::disk('public')->delete($user->avatar);
                }

                // 上传新头像
                $avatarPath = $request->file('avatar')->store('avatars/'.date('Ym'), 'public');
                $updateData['avatar'] = $avatarPath;
            }

            // 更新用户信息
            $user->update($updateData);

            return response()->json([
                'success' => true,
                'message' => '个人信息更新成功',
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'nickname' => $user->nickname,
                    'phone' => $user->phone,
                    'email' => $user->email,
                    'avatar' => $user->avatar ? Storage::url($user->avatar) : null,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新失败，请重试'
            ], 500);
        }
    }

    /**
     * 修改用户密码
     */
    public function changePassword(Request $request)
    {
        try {
            $user = Auth::user();

            // 验证输入数据
            $validator = Validator::make($request->all(), [
                'current_password' => 'required',
                'password' => ['required', 'confirmed', Password::min(6)],
            ], [
                'current_password.required' => '请输入当前密码',
                'password.required' => '请输入新密码',
                'password.min' => '新密码至少6位',
                'password.confirmed' => '两次输入的新密码不一致',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 验证当前密码
            if (!Hash::check($request->current_password, $user->password)) {
                return response()->json([
                    'success' => false,
                    'message' => '当前密码错误',
                    'errors' => [
                        'current_password' => ['当前密码错误']
                    ]
                ], 422);
            }

            // 检查新密码是否与当前密码相同
            if (Hash::check($request->password, $user->password)) {
                return response()->json([
                    'success' => false,
                    'message' => '新密码不能与当前密码相同',
                    'errors' => [
                        'password' => ['新密码不能与当前密码相同']
                    ]
                ], 422);
            }

            // 更新密码
            $user->update([
                'password' => Hash::make($request->password)
            ]);

            return response()->json([
                'success' => true,
                'message' => '密码修改成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '修改失败，请重试'
            ], 500);
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        try {
            $user = Auth::user();

            return response()->json([
                'success' => true,
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'phone' => $user->phone,
                    'email' => $user->email,
                    'created_at' => $user->created_at->format('Y-m-d H:i:s'),
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取用户信息失败'
            ], 500);
        }
    }
}
